package com.nut.course.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nut.course.api.req.ChangePasswordReq;
import com.nut.course.api.req.LoginReq;
import com.nut.course.api.req.RegisterReq;
import com.nut.course.api.resp.UserAuth;
import com.nut.course.common.Result;
import com.nut.course.entity.Partner;
import com.nut.course.entity.PartnerTeacher;
import com.nut.course.interceptor.JwtTokenUtil;
import com.nut.course.interceptor.UserJwt;
import com.nut.course.mapper.BizPartnerMapper;
import com.nut.course.service.PartnerService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;

@Slf4j
@Service
public class PartnerServiceImpl implements PartnerService {

    @Autowired
    private BizPartnerMapper bizPartnerMapper;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Result register(RegisterReq registerReq) {

        String mobile = registerReq.getMobile();
        String name = registerReq.getName();
        String password = registerReq.getPassword();

        if (StringUtils.isEmpty(mobile) || StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            return Result.fail("参数不能为空");
        }

        List<Partner> partners = bizPartnerMapper.selectList(new LambdaQueryWrapper<Partner>().eq(Partner::getName, name));
        if (partners.size() > 0) {
            return Result.fail("机构名称已存在");
        }

        partners = bizPartnerMapper.selectList(new LambdaQueryWrapper<Partner>().eq(Partner::getMobile, mobile));
        if (partners.size() > 0) {
            return Result.fail("手机号已存在");
        }

        Partner partner = new Partner();
        partner.setName(name);
        partner.setMobile(mobile);
        partner.setPassword(passwordEncoder.encode(password));

        bizPartnerMapper.insert(partner);

        return Result.ok();
    }

    @Override
    public Result<UserAuth> login(LoginReq loginReq) {

        String mobile = loginReq.getMobile();
        Partner partner = bizPartnerMapper.selectOne(
                new LambdaQueryWrapper<Partner>().
                        eq(Partner::getMobile, mobile));

        if (partner == null) {
            return Result.fail("账号不存在");
        }

        if (!passwordEncoder.matches(loginReq.getPassword(), partner.getPassword())) {
            return Result.fail("密码有误");
        }

        UserJwt userJwt = new UserJwt();
        userJwt.setUserId(partner.getId().toString());
        userJwt.setUsername(partner.getMobile());

        String token = jwtTokenUtil.generateToken(userJwt);
        UserAuth userAuth = new UserAuth();
        userAuth.setToken(token);

        return Result.ok(userAuth);

    }

    @Override
    public Result changePassword(ChangePasswordReq changePasswordReq) {

        Integer id = changePasswordReq.getId();
        Partner partner = bizPartnerMapper.selectById(id);

        if (partner == null) {
            return Result.fail("找不到机构信息");
        }

        String password = changePasswordReq.getPassword();
        String newPassword = changePasswordReq.getNewPassword();

        if (!passwordEncoder.matches(password, partner.getPassword())) {
            return Result.fail("原密码错误");
        }

        Partner update = new Partner();
        update.setId(id);
        update.setPassword(passwordEncoder.encode(newPassword));
        bizPartnerMapper.updateById(update);

        return Result.ok();
    }

    @Override
    public Result<IPage<Partner>> list(String status, String name, Integer pageNo, Integer pageSize) {
        Page<Partner> page = new Page<>();
        page.setSize(pageSize);
        page.setCurrent(pageNo);

        LambdaQueryWrapper<Partner> queryWrapper = new LambdaQueryWrapper<>();

        //排除 profile
        queryWrapper.select(Partner.class, a -> !a.getColumn().equals("profile"));

        if (StringUtils.hasLength(status)) {
            String[] statusIds = status.split(",");
            queryWrapper.in(Partner::getStatus, statusIds);
        }
        if (StringUtils.hasLength(name)) {
            queryWrapper.like(Partner::getName, name);
        }

        queryWrapper.orderByDesc(Partner::getId);

        IPage<Partner> list = bizPartnerMapper.selectPage(page, queryWrapper);
        return Result.ok(list);
    }

    @Override
    public Result<Partner> getById(Integer id) {
        Partner partner = bizPartnerMapper.selectById(id);
        return Result.ok(partner);
    }

    @Override
    public Result updateById(Partner partner) {
        bizPartnerMapper.updateById(partner);
        return Result.ok();
    }

    @Override
    public Result deleteByIds(Set<Integer> ids) {
        bizPartnerMapper.deleteBatchIds(ids);
        return Result.ok();
    }

}
